package org.csu.code.api.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.apache.catalina.User;
import org.csu.code.api.common.CommonResponse;
import org.csu.code.api.entity.*;
import org.csu.code.api.entity.Rent;
import org.csu.code.api.persistence.FarmMapper;
import org.csu.code.api.persistence.RentMapper;
import org.csu.code.api.persistence.SequenceMapper;
import org.csu.code.api.service.RentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import static org.yaml.snakeyaml.nodes.NodeId.sequence;

@Service("rentService")
public class RentServiceImpl implements RentService {
    @Autowired
    private RentMapper rentMapper;
    @Autowired
    private FarmMapper farmMapper;
    @Autowired
    private SequenceMapper sequenceMapper;
    @Override
    public CommonResponse<List<Rent>> getRentsByUserId(int userId) {
        QueryWrapper<Rent> queryWrapper= new QueryWrapper<>();
        queryWrapper.eq("userid",userId);
        List<Rent> rentList = rentMapper.selectList(queryWrapper);
        if(rentList.isEmpty()) {
            return CommonResponse.createForError("该用户没有租赁土地！");
        }
        return CommonResponse.createForSuccess(rentList);
    }

    @Override
    public CommonResponse<Rent> getRentByRentId(int rentId) {
        Rent rent = rentMapper.selectById(rentId);
        if(rent==null){
            return CommonResponse.createForError("没有该租赁号对应的租赁！");
        }
        return CommonResponse.createForSuccess(rent);
    }

    @Override
    public CommonResponse<List<Rent>> getRentsByFarmerId(int farmerId) {
        //通过farmerId找到对应的农场
        QueryWrapper<Farm> queryWrapper = new QueryWrapper<Farm>();
        queryWrapper.eq("userid", farmerId);
        Farm farm = farmMapper.selectOne(queryWrapper);
        if(farm==null){
            return CommonResponse.createForError("找不到该用户对应的农场！");
        }
        //将农场id用来查询对应的租赁
        QueryWrapper<Rent> rentQueryWrapper = new QueryWrapper<Rent>();
        rentQueryWrapper.eq("farmid", farm.getFarmId());
        List<Rent> rentList = rentMapper.selectList(rentQueryWrapper);
        if(rentList.isEmpty()){
            return CommonResponse.createForError("找不到该用户农场的租赁！");
        }
        return CommonResponse.createForSuccess(rentList);
    }

    @Override
    public CommonResponse<String> rent(Rent rent) {
        //判断是否有足够的土地，没有则返回不可以租赁
        Farm farm = farmMapper.selectById(rent.getFarmid());
        System.out.println(rent.toString());
        if(farm==null){
            return CommonResponse.createForError("农场不存在！");
        }
        double leftArea = farm.getLeftArea();
        if(leftArea < rent.getRentArea()){
            return CommonResponse.createForError("农场剩余面积不够！");
        }
        //修改数据库：新增一条Rent
        int rentId = getNextId("rentnum");
        rent.setRentid(rentId);
        Date currentDate = new Date();
        rent.setStartTime(currentDate);
        //获取租赁期限截止的时间
        Calendar endTime = Calendar.getInstance();
        endTime.setTime(currentDate);
        endTime.add(Calendar.DAY_OF_YEAR, rent.getLength());
        rent.setEndTime(endTime.getTime());
        rent.setStatus(0);
        rentMapper.insert(rent);
        return CommonResponse.createForSuccess("申请成功！");
    }

    @Override
    public CommonResponse<String> handle(int rentId, StatusMessage statusMessage) {
        Rent rent = rentMapper.selectById(rentId);
        if(rent == null){
            return CommonResponse.createForError("没有租赁号对应的租赁！");
        }
        //判断是否有足够的土地，没有则返回不可以租赁
        Farm farm = farmMapper.selectById(rent.getFarmid());
        double leftArea = farm.getLeftArea();
        if(leftArea < rent.getRentArea()){
            rent.setStatus(2);
            rent.setOthers2("农场剩余面积不够！");
            return CommonResponse.createForError("农场剩余面积不够！");
        }
        //设置状态
        rent.setStatus(statusMessage.getStatus());
        rent.setOthers2(statusMessage.getMessage());
        rentMapper.updateById(rent);
        //修改农场剩余面积
        farm.setLeftArea(leftArea - rent.getRentArea());
        farmMapper.updateById(farm);
        return CommonResponse.createForSuccess("处理申请成功！");
    }

    @Override
    public CommonResponse<Rent> deleteRent(int rentId) {
        Rent rent = rentMapper.selectById(rentId);
        if(rent == null){
            return CommonResponse.createForError("没有租赁号对应的租赁！");
        }
        rentMapper.deleteById(rentId);
        return CommonResponse.createForSuccess(rent);
    }

    @Override
    public int getNextId(String name) {
        Sequence sequence = new Sequence(name, -1);
        QueryWrapper<Sequence> sequenceQueryWrapper = new QueryWrapper<>();
        sequenceQueryWrapper.like("name",name);
        sequence = sequenceMapper.selectOne(sequenceQueryWrapper);
        if (sequence == null) {
            throw new RuntimeException("Error: A null sequence was returned from the database (could not get next " + name
                    + " sequence).");
        }
        Sequence parameterObject = new Sequence(name, sequence.getNextId() + 1);
        sequenceMapper.updateById(parameterObject);
        return sequence.getNextId();
    }
}
